﻿using System;
using System.Collections.Generic;
using K9Nano.Caching;
using K9Nano.Dependency;
using Microsoft.AspNetCore.Authentication;

namespace K9Nano.Admin.Weixin.OAuth
{
    internal class CachedPropertiesSecureDataFormat : ICachedPropertiesSecureDataFormat, ISingletonDependency
    {
        private readonly ITypedCache<AuthenticationPropertiesCache> _cache;

        public CachedPropertiesSecureDataFormat(ITypedCache<AuthenticationPropertiesCache> cache)
        {
            _cache = cache;
        }

        public string Protect(AuthenticationProperties data)
        {
            return Protect(data, null);
        }

        public string Protect(AuthenticationProperties data, string purpose)
        {
            var key = Guid.NewGuid().ToString();
            var cacheData = new AuthenticationPropertiesCache
            {
                Items = data.Items,
                WeixinAppSetting = (WeixinAppSettingInfo)data.Parameters[WeixinOAuthHandler.WeixinSettingKey]
            };

            _cache.Put(key, cacheData, TimeSpan.FromMinutes(5));
            return key;
        }

        public AuthenticationProperties Unprotect(string protectedText)
        {
            return Unprotect(protectedText, null);
        }

        public AuthenticationProperties Unprotect(string protectedText, string purpose)
        {
            var key = protectedText;
            var data = _cache.Get(key);
            var properties = new AuthenticationProperties(data.Items, new Dictionary<string, object>
            {
                {WeixinOAuthHandler.WeixinSettingKey, data.WeixinAppSetting}
            });
            return properties;
        }
    }

    internal class AuthenticationPropertiesCache
    {
        public IDictionary<string, string> Items { get; set; }

        public WeixinAppSettingInfo WeixinAppSetting { get; set; }
    }
}